package src.queue;

/**
 * @author Dream
 */
public class ArrayQueue<T> {
    private final Object[] array;
    private int rear = 0;

    public ArrayQueue(int length) {
        array = new Object[length];
    }

    /**
     * 插入
     */
    public void add(T item) {
        if (item == null) {
            System.out.println("插入失败：元素不能为空");
            return;
        }
        try {
            array[rear] = item;
            rear++;//成功后自增
        } catch (Exception e) {
            System.out.println("插入失败,队列已满");
        }
    }

    /**
     * 移除头部元素
     */
    public T remove() {
        if (isEmpty()) {
            System.out.println("无元素");
            return null;
        }
        try {
            int i = 0;
            T t = (T) array[0];
            for (int j = 0; j < rear - 1; j++) {
                array[j] = array[j + 1];
                i++;
            }
            rear = i;
            return t;
        } catch (Exception e) {
            System.out.println("移除失败");
        }
        return null;

    }

    /**
     * 获取头部元素
     */
    public T peek() {
        if (isEmpty()) {
            System.out.println("无元素");
            return null;
        }
        T t = (T) array[0];
        return t;
    }

    public int size() {
        return rear;
    }

    public boolean isEmpty() {
        if (rear == 0) {
            return true;
        }
        return false;
    }
}
